﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Celeriq.QueryLog
{
	public class QueryLogger
	{
		private string _path;
		private object _locker = new object();
		
		public QueryLogger(string path)
		{
			if (!Directory.Exists(path))
			{
				throw new Exception("The path '" + path + "' does not exist!");
			}
			_path = path;
		}

		public void Log(string query, int elapsed, int count, bool fromcache)
		{
			lock (_locker)
			{
				var fileName =this.FileName;
				if (!File.Exists(fileName))
				{
					var header = "#Software: Widgetsphere Celeriq Server\r\n" +
					"#Version: 2.0\r\n" +
					"#Date: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" +
					"#Fields: date ip count time-taken cache query\r\n";
					File.AppendAllText(fileName, header);
				}

				var line = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ff") + "\t" + this.CallerAddress + "\t" + count + "\t" + elapsed + "\t" + (fromcache ? "1" : "0") + "\t" + query + "\r\n";
				File.AppendAllText(fileName, line);
			}
		}

		private string FileName
		{
			get
			{
				var retval = DateTime.Now.ToString("yyyy-MM-dd");
				retval = Path.Combine(_path, retval) + ".query.log";
				return retval;
			}
		}

		private string CallerAddress
		{
			get
			{
				if (System.ServiceModel.OperationContext.Current != null)
				{
					if (System.ServiceModel.OperationContext.Current.IncomingMessageProperties != null)
					{
						var o = System.ServiceModel.OperationContext.Current.IncomingMessageProperties["System.ServiceModel.Channels.RemoteEndpointMessageProperty"] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
						if (o != null)
						{
							return o.Address;
						}
					}
				}
				return string.Empty;
			}
		}

	}
}
